from masoniteorm.schema import Schema
from loguru import logger

from application.config.database import DB
from ..base import BaseModel


class Code(BaseModel):
    __connection__ = 'postgres'


def get_code_model(prefix):
    prefix = prefix.lower()
    table_name = 'code_%s' % prefix
    logger.info('=======================CODE table_name %s' % table_name)

    # 动态创建表
    mSchema = Schema(connection=Code.__connection__, connection_details=DB.get_connection_details())
    # 如果没有表则创建
    logger.info(f'=======================CODE has_table {table_name} {mSchema.has_table(table_name)}')
    if not mSchema.has_table(table_name):
        with mSchema.create(table_name) as table:
            table.big_increments('id').primary()
            table.string('import_key', 32, True).index()
            table.string('batch_sn', 32, True)
            table.integer('batch_num', 11, True)
            table.string('big_code', 32, True).index()
            table.string('big_verify_code', 32, True)
            table.string('middle_code', 32, True).index()
            table.string('middle_verify_code', 32, True)
            table.string('small_code', 32, True).index()
            table.string('serial_code', 32, True)
            table.string('security_code', 32, True).index()
            table.string('verify_code', 32, True)
            table.integer('query_type', 11, True)
            table.integer('status', 11, True).index()
            table.integer('activated_stat', 11, True).index()
            # created_at/updated_at
            table.timestamp('created_at', True, True)
            table.timestamp('updated_at', True, True)

        logger.info('=======================CODE create table %s' % table_name)

    return Code.table(table_name)


__all__ = [
    'get_code_model',
]
